import React, { useEffect, useMemo, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { setToken } from '../../utils/auth';
import './login.css';
import phoprintLogo from '../../assets/phoprint-logo.svg';
import loginBanner from '../../assets/react.svg';

export default function Login() {
  const navigate = useNavigate();
  const location = useLocation();
  const from = location.state?.from?.pathname || '/';

  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [isRemember, setIsRemember] = useState(true);
  const [captchaUrl, setCaptchaUrl] = useState('');
  const [captchaCode, setCaptchaCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    const saved = localStorage.getItem('loginInfo');
    if (saved) {
      try {
        const obj = JSON.parse(saved);
        setUsername(obj.username || '');
        setPassword(obj.password || '');
      } catch {}
    }
    initCaptcha();
  }, []);

  function generateCaptchaDataUri(text) {
    const svg = `<?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" width="100" height="40"><rect width="100" height="40" fill="#f0f0f0"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-size="18" fill="#333" font-family="monospace">${text}</text></svg>`;
    return 'data:image/svg+xml;base64,' + btoa(svg);
  }

  function randomCode(len = 4) {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    let out = '';
    for (let i = 0; i < len; i++) out += chars[Math.floor(Math.random() * chars.length)];
    return out;
  }

  function initCaptcha() {
    const code = randomCode(4);
    setCaptchaUrl(generateCaptchaDataUri(code));
  }

  async function handleLogin(e) {
    e?.preventDefault?.();
    setError('');
    if (!username || !password) {
      setError('请输入用户名和密码');
      return;
    }
    if (captchaUrl && !captchaCode) {
      setError('请输入验证码');
      return;
    }
    setLoading(true);
    try {
      await new Promise(r => setTimeout(r, 600));
      setToken(`token_${Date.now()}`);
      if (isRemember) {
        localStorage.setItem('loginInfo', JSON.stringify({ username, password }));
      } else {
        localStorage.removeItem('loginInfo');
      }
      navigate(from, { replace: true });
    } catch (err) {
      setError('登录失败，请重试');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="login-page">
      <div className="login-card auto-bg">
        <div className="login-left">
          <img src={loginBanner} alt="login_banner" className="banner" />
        </div>
        <div className="login-right">
          <h2 className="login-title">
            <img src={phoprintLogo} height="50" className="logo" alt="logo" />
            <span>商户端后台</span>
          </h2>

          <form onSubmit={handleLogin} className="login-form">
            <div className="input with-prefix">
              <span className="prefix">👤</span>
              <input
                autoFocus
                type="text"
                placeholder="请输入用户名"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
              />
            </div>
            <div className="input with-prefix">
              <span className="prefix">🔒</span>
              <input
                type="password"
                placeholder="请输入密码"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter') handleLogin(e); }}
              />
            </div>

            <div className="captcha-row">
              <div className="input with-prefix">
                <span className="prefix">🔑</span>
                <input
                  type="text"
                  maxLength={4}
                  placeholder="请输入验证码"
                  value={captchaCode}
                  onChange={(e) => setCaptchaCode(e.target.value)}
                  onKeyDown={(e) => { if (e.key === 'Enter') handleLogin(e); }}
                />
              </div>
              {captchaUrl && (
                <img
                  src={captchaUrl}
                  alt="验证码"
                  className="captcha-img"
                  height="40"
                  onClick={initCaptcha}
                />
              )}
            </div>

            <label className="checkbox">
              <input type="checkbox" checked={isRemember} onChange={(e) => setIsRemember(e.target.checked)} />
              <span>记住密码</span>
            </label>

            {error && <div className="error-tip">{error}</div>}

            <div className="btn-row">
              <button type="button" className="btn ghost" title="建议使用强密码，开启两步验证">安全提示</button>
              <button type="submit" className="btn primary" disabled={loading}>
                {loading ? '登录中…' : '登录'}
              </button>
            </div>
          </form>
        </div>
      </div>

      <div className="login-footer">© 2025 React Ruiye</div>
    </div>
  );
}